<?php
namespace App\Http\Controllers\Api\Activity;

use App\Http\Controllers\Controller;

use App\Models\Activity\StoreGift;

use App\Models\Activity\StoreGiftPartake;

use App\Models\Activity\StoreGiftPrize;

use App\Models\Activity\StoreGiftReceive;

use App\Models\Card\CardCoupon;

use App\Models\Customer\Customer;

use App\Models\Mall\MallGroup;

use App\Service\CardService;

use App\Models\Card\CardCouponCode;

use Carbon\Carbon;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use App\Models\ConfigureFunction;

use Illuminate\Support\Facades\Redis as Redis;

class StoreGiftController extends Controller {

    /**
     * 初始化接口
     * @param Request $request
     * @return mixed
     */
    public function init ( Request $request ) {

        $mallID = $request->input('mallID',0);
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id');
        if ( !$session_id ) {
            $session_id = session_id();
        }

        if ( $platform != 6 ) {
            $is_open_choose_mall = ConfigureFunction::getConfigureField(8,'is_open_choose_mall');
            if ( $is_open_choose_mall ) {
                $choose_mall_id = redisTransformation( Redis::get($session_id.'G_CHOOSE_MALL_ID'));
                if ( $choose_mall_id ) {
                    $mallID = $choose_mall_id;
                }
            }
        } else {
            if ( !$mallID || !ebsig_is_int( $mallID , 2 ) ) {
                return response()->json(['code' => 10001, 'message' => '请选择门店']);
            }
        }

        //查询当前进店有礼活动
        $store_gift_data = StoreGift::getCache();
        if ( !$store_gift_data || $store_gift_data['receive_status'] == 3 ) {
            return response()->json(['code' => 10001, 'message' => '当前没有活动']);
        }

        //查询活动奖品
        $prize_data = StoreGiftPrize::getList([
            'activity_id'=>$store_gift_data['activity_id'],
        ]);

        if ( empty( $prize_data ) ) {
            return response()->json(['code' => 10006, 'message' => '没有活动奖品']);
        }

        //活动平台
        if ( !in_array( $platform , $store_gift_data['platform'] ) ){
            return response()->json(['code' => 10002, 'message' => '平台不在活动范围内']);
        }

        //指定活动门店
        if ( $store_gift_data['mall_type'] == 2 ) {

            if ( !isset( $store_gift_data['mall_group_id'] ) || !ebsig_is_int( $store_gift_data['mall_group_id'] ) ) {
                return response()->json(['code' => 10002, 'message' => '未指定门店']);
            }

            $mall_group = MallGroup::getCache( $store_gift_data['mall_group_id'] );
            if ( !isset( $mall_group['map'][$mallID] ) ) {
                return response()->json(['code' => 10003, 'message' => '门店不在活动范围内']);
            }

        }

        $data = [
            'activity_name' => $store_gift_data['activity_name'],
            'activity_id' => $store_gift_data['activity_id'],
            'template_id' => $store_gift_data['template_id'],
            'template_pic' => $store_gift_data['template_pic'],
        ];

        return response()->json(['code' => 200 , 'message' => 'ok' , 'data' => $data ]);

    }


    /**
     * 发放奖品
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function send( Request $request ) {

        $activity_id = $request->input('activity_id',0);    //防止登陆后。两个活动正在交替时。可不传
        $mallID = $request->input('mallID',0);
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id');
        if ( !$session_id ) {
            $session_id = session_id();
        }

        //查询会员信息
        $cust_data = get_customer_login( $session_id , $platform );
        $pcustID = $cust_data['pcustID'];
        $custID = $cust_data['custID'];

        if ( !$pcustID ) {
            return response()->json(['code' => 10001, 'message' => '未登录']);
        }

        if ( $platform != 6 ) {
            $is_open_choose_mall = ConfigureFunction::getConfigureField(8,'is_open_choose_mall');
            if ( $is_open_choose_mall ) {
                $choose_mall_id = redisTransformation( Redis::get($session_id.'G_CHOOSE_MALL_ID'));
                if ( $choose_mall_id ) {
                    $mallID = $choose_mall_id;
                }
            }
        } else {
            if ( !$mallID || !ebsig_is_int( $mallID , 2 ) ) {
                return response()->json(['code' => 10002, 'message' => '缺少门店信息']);
            }
        }

        //查询当前进店有礼活动
        $store_gift_data = StoreGift::getCache();
        if ( !$store_gift_data || $store_gift_data['receive_status'] == 3 ) {
            return response()->json(['code' => 10004, 'message' => '活动已结束']);
        }

        if ( $activity_id > 0 ) {
            if ( $activity_id !=  $store_gift_data['activity_id'] ) {
                return response()->json(['code' => 10005, 'message' => '活动已结束']);
            }
        }

        //会员已参与过该活动
        if ( StoreGiftPartake::getPartake( $pcustID , $store_gift_data['activity_id'] ) ) {
            return response()->json(['code' => 10003, 'message' => '活动已参与']);
        }

        //活动平台
        if ( !in_array( $platform , $store_gift_data['platform'] ) ){
            return response()->json(['code' => 10006, 'message' => '当前平台没有活动']);
        }

        //指定活动门店
        if ( $store_gift_data['mall_type'] == 2 ) {

            if ( !isset( $store_gift_data['mall_group_id'] ) || !ebsig_is_int( $store_gift_data['mall_group_id'] ) ) {
                return response()->json(['code' => 10002, 'message' => '未指定门店']);
            }

            $mall_group = MallGroup::getCache( $store_gift_data['mall_group_id'] );
            if ( !isset( $mall_group['map'][$mallID] ) ) {
                return response()->json(['code' => 10003, 'message' => '门店不在活动范围内']);
            }

        }

        //用户类型
        $cust_type = 1;

        //查询会员信息
        $cust_data = Customer::find( $pcustID );
        if ( $cust_data ) {
            if ( $cust_data['createTime'] < $store_gift_data['start_time'] ) {
                $cust_type = 2;
            }
        }

        //查询活动奖品
        $prize_data = StoreGiftPrize::getList([
            'activity_id'=>$store_gift_data['activity_id'],
            'customer_type'=>$cust_type
        ]);

        if ( empty( $prize_data ) ) {

            StoreGiftPartake::savePartake( $store_gift_data['activity_id'] , $pcustID , $custID , '0' , '当前会员类型没有设置活动奖品');

            // 新人、老人用不同的code，用于前台展示不同弹层
            $code = 10014;
            if ( $cust_type == 2 ) {
                $code = 10009;
            }
            return response()->json(['code' =>$code , 'message' => '当前会员类型没有设置活动奖品']);
        }

        //老用户等级判断
        if ( !empty( $prize_data[0]['customer_rank'] ) ) {
            if ( !in_array( $cust_data['rankID'] , explode(',',$prize_data[0]['customer_rank']) ) ) {
                StoreGiftPartake::savePartake( $store_gift_data['activity_id'] , $pcustID , $custID , '0' , '会员等级不在活动范围内');
                return response()->json(['code' => 10008, 'message' => '会员等级不在活动范围内']);
            }
        }

        //实例卡券服务类
        $card_service = new CardService();

        try {

            //开始事务
            DB::beginTransaction();

            $data = [
                'template_id' => $store_gift_data['template_id'],
                'gift' => []
            ];

            //卡券发放记录
            $send_log = [];

            //更新主表活动状态
            $is_upate = true;

            //会员发放卡券
            foreach ( $prize_data as $prize ) {

                //活动卡券库存
                if ( $prize['receive_num'] >= $prize['total_num'] ) {
                    $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 0 , 'message' => '活动设定卡券数已发放完'];
                    continue;
                }

                //活动剩余可发数量
                if ( $prize['grant_num'] > ( $prize['total_num'] - $prize['receive_num'] ) ) {
                    $prize['grant_num'] = $prize['total_num'] - $prize['receive_num'];
                }

                $is_upate = false;

                /**
                 * 检查卡券信息
                 */
                $card_data = CardCoupon::find( $prize['card_id'] );

                if ( !$card_data ) {
                    $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 0 , 'message' => '卡券不存在'];
                    continue;
                } else {
                    $card_data = $card_data->toArray();
                }

                if ( $card_data['useFlg'] == 0 ) {
                    $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 0 , 'message' => '该卡券已禁用'];
                    continue;
                }

                if ( $card_data['provide_type'] == 1 ) {
                    if ( $card_data['start_time'] > Carbon::now() || $card_data['end_time'] < Carbon::now() ) {
                        $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 0 , 'message' => '卡券不在发放时间范围内'];
                        continue;
                    }
                } else {
                    $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 0 , 'message' => '该卡券不是账户券，无法发放'];
                    continue;
                }

                if ( $card_data['repeat_count'] > 0 ) {
                    $search_num =  CardCouponCode::where(['activity_id'=>$card_data['card_id'],'pcustID'=>$pcustID])->count();
                    if ( $search_num >=  $card_data['repeat_count']  ) {
                        $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 0 , 'message' => '卡券已超出重复领取次数'];
                        continue;
                    }
                }

                //卡券剩余数量
                $surplus = $card_data['total_num']-$card_data['getNum'];
                if ( $surplus <= 0 ) {
                    $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 0 , 'message' => '卡券数量不足'];
                    continue;
                }

                if ( $prize['grant_num'] > $surplus ) {
                    $prize['grant_num'] = $surplus;
                }

                //卡券实际发放数量
                $receive_num = 0;

                for ( $i = 0 ; $i < $prize['grant_num'] ; $i++ ) {

                    $send_result = $card_service->grant( $card_data , 1 , $pcustID , $custID , false );

                    if ( $send_result['code'] != 200 ) {
                        $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 0 , 'message' => $send_result['message']];
                    } else {
                        $receive_num++;
                        $send_log[] = ['card_id'=> $prize['card_id'] , 'code' => 1 , 'message' => 'ok'];
                    }

                }

                //当实际发放数量大于0时
                if ( $receive_num > 0 ) {

                    //更新活动领取数量
                    StoreGiftPrize::where([
                        'activity_id'=>$store_gift_data['activity_id'],
                        'id' => $prize['id'],
                        'card_id' => $prize['card_id']
                    ])->increment('receive_num', $receive_num);

                    //返回卡券信息
                    $data['gift'][] = [
                        'discount' => $card_data['discount']*10,
                        'amount' => floatval( $card_data['amount'] ),
                        'card_type' => $card_data['card_type'],
                        'use_start_time' => str_replace('-','.',explode(' ' , $card_data['use_start_time'])[0]),
                        'use_end_time' => str_replace('-','.',explode(' ' , $card_data['use_end_time'])[0]),
                        'description' => $card_data['description'],
                        'limit_money' => $card_data['limit_money'],
                        'card_name' => $prize['card_name'],
                        'receive_num' => $receive_num
                    ];
                }
            }

            if (  $is_upate  ) {

                if ( $cust_type != $store_gift_data['receive_status'] ) {

                    $status = $store_gift_data['receive_status'] + $cust_type;

                    StoreGift::where('activity_id', $store_gift_data['activity_id'])->increment('receive_status', $status);

                    Redis::del('G_WDH_STORE_GIFT');

                }

            }

            //卡券发放记录
            if ( !empty( $send_log ) ) {
                foreach ( $send_log as $send ) {
                    StoreGiftReceive::insert([
                        'uuid' => makeUuid(),
                        'timeStamp' => Carbon::now(),
                        'creator' => 'system',
                        'createTime' => Carbon::now(),
                        'activity_id' => $store_gift_data['activity_id'],
                        'pcustID' => $pcustID,
                        'card_id' => $send['card_id'],
                        'status_code' => $send['code'],
                        'error_msg' => $send['message']
                    ]);
                }
            }

            if ( empty( $data['gift'] ) ) {
                StoreGiftPartake::savePartake( $store_gift_data['activity_id'] , $pcustID , $custID , '0' , '卡券发放失败');
            } else {
                StoreGiftPartake::savePartake( $store_gift_data['activity_id'] , $pcustID , $custID , '1' , 'ok');
            }

            //提交事务
            DB::commit();

            if ( empty( $data['gift'] ) ) {
                return response()->json(['code' => 10013 , 'message' => '奖品已发完']);
            } else {
                return response()->json(['code' => 200, 'message' => '卡券发放成功' , 'data' => $data ]);
            }

        } catch (Exception $e) {

            //事务回滚
            DB::rollBack();

            return response()->json(['code' => 10012 , 'message' => '卡券发放失败']);

        }

    }

}